$('.play-img').masonry({
    transitionDuration: 0
});

var start = 1;//页面刚加载好之后请求的数据;
var index = 8;//以后每次加载请求的数据;
//var count = 4;
var isLord = true;

var timer = null;

load();
//把处理数据的功能封装成一个方法;
function handleData(res){
    var str = '';
    $.each(res.data, function (index, item) {
        item['time'] = '1小时前';
        item['pageUrl'] = 'http://www.jiguo.com/' + item['pageUrl'];
        str += `<div class="box">
               <div class="box-img">
                   <img src="${item.imgUrl}" alt="">
               </div>
               <div class="info">
                   <p><a href="${item.pageUrl}">${item.title}</a></p>
               </div>
               <div class="box-bottom">
                   <span class="fl info-com">${item.type}</span>
                   <span class="fr time">${item.time}</span>
               </div>
           </div>`
    });
    //   console.log(str);
    $('.play-img').masonry({
        transitionDuration: 0
    }).append(str).masonry('appended', str).masonry();
}


//实现滚动加载更多;
$(window).scroll(function(){
    clearTimeout(timer);
    var that = $(this);
    timer = setTimeout(function(){
        //窗口被卷去的头部
        var scrollH = that.scrollTop();
        //获取窗口的高度
        var clientH = $(window).height();
        //当滚动到最后一张图片距顶部的高度时就加载数据;
        var lastTop = $('.box:last').offset().top;
        //最后一张图片的高度;
        var h = ($('.box:last').height()) / 2;
        if (scrollH + clientH >= lastTop + h) {
            console.log('可以加载数据了~');
            if (!isLord) {
                return;
            }
            load();
        }
    },200)
});

//定义一个加载数据的方法;
function load(){
    console.log(index);
    isLoad = false;
    //flag = true;
    $.ajax({
        url:'http://api.jg.com/goods/products',
        method:'post',
        dataType:'json',
        data:{
            start:start,
            currentNum:index
        },
        success:function(res){
            console.log(res);
            handleData(res);
            isLord = true;
            start = index+1;
            index+=res.data.length;
        }
    })
}



